/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head == null||head.next == null) {
            return null;
        }
        ListNode slow = head,fast = head;
        //一开始flag定义为无环
        boolean flag = false;
        while(fast!=null&&fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast) {
                //有环
                flag = true;
                break;
            }
        }
        if(flag == false) {
            return null;
        }
        slow = head;
        while(slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }
}